const puppeteer = require('puppeteer');
const fs = require('fs');
const request = require('request');
const path = require('path');


const loginUrl = 'https://account.geekbang.org/signin?redirect=https%3A%2F%2Ftime.geekbang.org%2F'   //登陆地址
const listUrl = 'https://time.geekbang.org/column/intro/341'   //课程列表
const file = 'jkTime/yhty/'                             //目标保存文件夹
const fileName = '.cZCVMzBP_0'                         //爬取页面标题作为次此文件名字
const WechaLogin = '/html/body/div[1]/div[2]/div/div[4]/ul/li[1]'              //微信xpath
const tabListXp = '/html/body/div[1]/div[1]/div[3]/div[1]/div[1]/a[2]'              //列表xpath
const audioXp = '//*[@id="app"]/div[1]/div[2]/div[2]/div/div[1]/div[2]/div/div/div/div/div[2]/div[2]/audio'              //audioXpath

async function getPhoto() {
    let browser = await puppeteer.launch({
        headless: false,        //开启视图
        defaultViewport: null,
    });
    let page = await browser.newPage();
    console.log('······打开页面······')
    await page.goto(loginUrl);
    console.log('······请在5秒内登陆······')
    popLogin = await page.$x(WechaLogin)
    await popLogin[0].click()
    await page.waitForTimeout(5000)
    await page.goto(listUrl);
    await page.waitForTimeout(800)
    tabList = await page.$x(tabListXp)
    await tabList[0].click()
    await page.waitForTimeout(1500)
    let items = await page.$$eval('section a', el => el.map(x => x.getAttribute("href")));   // 获取列表 a 链接 href
    console.log('······采集链接-结束······')
    // console.log(items)
    for (let item of items) {
        if (item != 'javascript:;') {
            console.log('······打开页面' + item + '······')
            await page.goto('https:' + item);
            await page.waitForTimeout(2000)
            let title = await page.$(fileName);
            let name = await (await title.getProperty('innerText')).jsonValue(); // 获取名称
                console.log('······📃 ' + name + '开始保存······')
                let html = await page.content();
                
                // 将html保存到一个文件中
                fs.writeFileSync(file + name + '.html', html, _ => console.log('HTML saved'));
                console.log('······HTML saved 👌······')
                // 追加自定义代码
                audioTF = await page.$x(audioXp)
                // console.log(audioTF)
            if (audioTF.length > 0) {
                let audio = await page.$eval('audio', el => el.src);
                // console.log(audio)
                let addJavaScript = `
                    <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
                    <script>
                    var x = document.createElement("AUDIO");
                    x.setAttribute("id", "myAudio");
                    document.body.appendChild(x);
                    setTimeout(function () {
                        var audio = document.getElementById("myAudio");
                        console.log(audio)
                        document.getElementsByClassName("_1fyhPbAt_0")[0].addEventListener("click", function () {
                        if (Hls.isSupported()) {
                            var hls = new Hls();
                            hls.loadSource('${audio}');
                            hls.attachMedia(audio);
                            hls.on(Hls.Events.MANIFEST_PARSED, function () {
                            console.log('play')
                            audio.play().then(() => {
                                console.log('success')
                            })
                                .catch((err) => {
                                console.log('err', err)
                                });
                            });
                        }
                        })
                        }, 2000)
                    </script>
                    `
                    fs.appendFileSync(file + name + '.html', addJavaScript, _ => console.log('HTML appendFile ✅ '));
                    console.log('······HTML appendFile ✅······')
            }
            }

        }
        // 关闭任务
        await browser.close();
    }
    getPhoto()

